# -*- coding: utf-8 -*-
from datetime import datetime
from typing import Optional
from typing_extensions import Self

from pydantic import EmailStr, Field, ConfigDict, model_validator

from App.app.admin.schemas.sys_role_schema import GetSysRoleListDetails
from App.common.schema import SchemaBase
from App.utils.enums import StatusType


class AuthSchemaBase(SchemaBase):
    """登录"""
    username: str
    password: str | None


class RegisterUserParam(AuthSchemaBase):
    nickname: str | None = None
    email: EmailStr = Field(examples=['user@example.com'])


class SysUserSchema(SchemaBase):
    model_config = ConfigDict(from_attributes=True)
    username: str
    nickname: str
    role_id: int | None
    email: EmailStr | None = None
    is_super: StatusType
    is_staff: StatusType
    status: StatusType
    is_multi_login: StatusType
    avatar: str | None = None
    phone: str | None = None
    des: str | None = None
    last_login_time: datetime | None = None


class CreateSysUserParam(SchemaBase):
    username: str
    nickname: str | None = None
    password: str | None = None
    role_id: int
    email: EmailStr | None = None
    phone: str | None = None
    is_super: StatusType = StatusType.disable.value
    is_staff: StatusType = StatusType.enable.value
    status: StatusType = StatusType.enable.value
    is_multi_login: StatusType = StatusType.disable.value


class UpdateSysUserParam(SchemaBase):
    id: int
    nickname: Optional[str] = None
    email: Optional[EmailStr] = None
    avatar: Optional[str] = None
    phone: Optional[str] = None


class UpdateMeParam(UpdateSysUserParam):
    des: Optional[str] = None


class GetSysUseInfoNoRoleDetail(SysUserSchema):
    """基础用户信息，无关联对象， 用于列表快速查询，避免JOIN操作"""
    model_config = ConfigDict(from_attributes=True)

    id: int
    created_time: datetime
    updated_time: datetime | None = None


class GetUserInfoDetails(GetSysUseInfoNoRoleDetail):
    """带完整关联信息的用户详情"""
    model_config = ConfigDict(from_attributes=True)
    last_login_time: datetime | None = None
    role: GetSysRoleListDetails | None = None


class GetCurrentUserInfoDetail(GetUserInfoDetails):
    """扁平化处理"""
    model_config = ConfigDict(from_attributes=True)

    # 字段类型覆盖
    role: GetSysRoleListDetails | str | None = None

    @model_validator(mode='after')
    def handel(self) -> Self:
        """将关联对象转换为名称"""
        if self.role:
            self.role = self.role.name  # 角色对象 → 角色名称
        return self


class CurrentUserInfo(GetUserInfoDetails):
    """系统内部传递"""
    model_config = ConfigDict(from_attributes=True)
    # 无新增字段，保持与父类完全一致的结构


class ResetPasswordParam(SchemaBase):
    old_password: str
    new_password: str
    repeat_password: str
